import java.io.IOException;
import java.io.ObjectInputStream;

public class Receiver implements Runnable {

    private ObjectInputStream m_in;
    private MessageQueue m_messageQueue;

    private boolean isReading;
    private int readBytes;
    private int messageLength;
    private int messageType;
    private  byte[] messageData;
    private Thread m_thread;



    public Receiver(ObjectInputStream in, MessageQueue messageQueue, int bufferSize)
    {
        m_in = in;
        m_messageQueue = messageQueue;
        messageData = new byte[bufferSize];
        m_thread = new Thread(this);
    }

    public void setDaemon(boolean isDaemon)
    {
        m_thread.setDaemon(isDaemon);
    }

    public void start()
    {
        m_thread.start();
    }

    public void run()
    {
        int byteCount;
        
        while (true)
        {
            try
            {
                //System.out.println(m_in.available());
                //if (m_in.available() <= 0)
                //    continue;
                if (!isReading)
                {
                    messageLength = m_in.readInt();
                    messageType = m_in.readInt();
                    //System.out.println("receive " + messageLength + " " + messageType + "\n");
                    isReading = true;
                    readBytes = 0;
                }
                byteCount = m_in.read(messageData, readBytes, messageData.length - readBytes);

                readBytes += byteCount;

                if (messageLength == readBytes)
                {
                    m_messageQueue.push(new Message(messageType, messageData, messageLength));
                    isReading = false;
                }
            }
            catch (IOException e)
            { }
        }
    }

    public void stop()
    {
        m_thread.interrupt();
    }
}

